package cn.joybreeze.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @ClassName JWTUtils
 * @Description
 * @Author Kjwaa
 * @Email 1135274290@qq.com
 * @Date 2021/5/6 15:50
 */
public class JWTUtils {
    private static final String SIGNATRUE = "!@$$@%%@#!"; //加密盐值

    /**
     * 生成token
     * header.payload.signature
     */
    public static String getToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        //默认是7天，这里测试就用九十秒吧
        instance.add(Calendar.SECOND, 3600);
        //创建JWTBuilder
        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim); //要确定参数类型才能这样写，如果有Object就不行
        String token = builder.withExpiresAt(instance.getTime()) //设置token过期时间
                .sign(Algorithm.HMAC256(SIGNATRUE));
        return token;
    }

    /**
     * 验证token
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SIGNATRUE)).build().verify(token);
    }
}

